package com.yanlight.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;

public class WxHttpClientUtil {

    // 连接超时时间，默认30秒
    private static int socketTimeout = 30000;

    // 传输超时时间，默认30秒
    private static int connectTimeout = 30000;


    /**
     * xml请求
     *
     * @param postData
     * @return
     */
    @SuppressWarnings("deprecation")
    public static String xmlPost(String url, String mchId, String certPath, String postData) {
        String result = null;
        try {
            KeyStore keyStore = getKeyStore(mchId, certPath);
            HttpPost httpPost = new HttpPost(url);

            SSLContext sslContext = SSLContexts.custom().loadKeyMaterial(keyStore, mchId.toCharArray()).build();

            SSLConnectionSocketFactory sslcs = new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1"}, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

            CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslcs).build();

            StringEntity postEntity = new StringEntity(postData, "UTF-8");
            httpPost.addHeader("Content-Type", "text/xml");
            httpPost.setConfig(getRequestConfig());
            httpPost.setEntity(postEntity);
            HttpResponse httpResponse = httpclient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity, "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 加载证书
     *
     * @return
     * @throws KeyStoreException
     * @throws FileNotFoundException
     */
    private static KeyStore getKeyStore(String mchId, String certPath)
            throws KeyStoreException, FileNotFoundException {
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        FileInputStream inputStream = new FileInputStream(new File(certPath));
        try {
            keyStore.load(inputStream, mchId.toCharArray());
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return keyStore;
    }

    /**
     * HTTP默认请求参数设置
     *
     * @return
     */
    private static RequestConfig getRequestConfig() {
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
        return requestConfig;
    }

}
